Popular New Releases in Code Inspection
dnSpy
v6.1.8
delve
v1.8.2
stetho
Release 1.6.0
chisel
Renames, Ranges, and the Copy Command
gdbgui
v0.15.0.1
Popular Libraries in Code Inspection
by x64dbg c++
37297 GPL-3.0
An open-source x64/x32 debugger for windows.
by dnSpy csharp
18900
.NET debugger and assembly editor
by go-delve go
18048 MIT
Delve is a debugger for the Go programming language.
by cool-RR python
14960 MIT
Never use print for debugging again
by zalmoxisus javascript
12927 MIT
Redux DevTools extension.
by node-inspector javascript
12564 BSD-2-Clause
Node.js debugger based on Blink Developer Tools
by facebook java
12302 MIT
Stetho is a debug bridge for Android applications, enabling the powerful Chrome Developer Tools and much more.
by brendangregg perl
11766
Stack trace visualizer
by GoogleChromeLabs javascript
10479 Apache-2.0
ndb is an improved debugging experience for Node.js, enabled by Chrome DevTools
Trending New libraries in Code Inspection
by Sysinternals c++
3077 MIT
Procmon is a Linux reimagining of the classic Procmon tool from the Sysinternals suite of tools for Windows. Procmon provides a convenient and efficient way for Linux developers to trace the syscall activity on the system.
by leon-thomm python
2490 MIT
Flow-based visual scripting for Python
by laike9m python
2020 MIT
Python debugging, redefined.
by gaogaotiantian python
1788 Apache-2.0
VizTracer is a low-overhead logging/debugging/profiling tool that can trace and visualize your python code execution.
by jerosoler javascript
1546 MIT
Simple flow library 🖥️🖱️
by vt-vl-lab python
1268 NOASSERTION
[ECCV 2020] Flow-edge Guided Video Completion
by sidkshatriya rust
835 NOASSERTION
rd is a record/replay debugger written in rust
by nguyenquangminh0711 ruby
820 MIT
Just Another Ruby Debugger. Provide a rich Terminal UI that visualizes everything your need, navigates your program with pleasure, stops at matter places only, reduces manual and mental efforts. You can now focus on real debugging.
by CCExtractor python
788 MIT
A simple Python debugger and profiler that generates animated visualizations of program flow, useful for algorithm learning.
Top Authors in Code Inspection
1
17 Libraries
7387
2
14 Libraries
1197
3
9 Libraries
1471
4
8 Libraries
191
5
8 Libraries
40661
6
8 Libraries
161
7
8 Libraries
4446
8
7 Libraries
50
9
6 Libraries
191
10
5 Libraries
24
1
17 Libraries
7387
2
14 Libraries
1197
3
9 Libraries
1471
4
8 Libraries
191
5
8 Libraries
40661
6
8 Libraries
161
7
8 Libraries
4446
8
7 Libraries
50
9
6 Libraries
191
10
5 Libraries
24
Trending Kits in Code Inspection
No Trending Kits are available at this moment for Code Inspection
Trending Discussions on Code Inspection
Expected type 'Type[Add | Sub | Mult | Div | Pow | BitXor | USub]', got 'Type[operator]' instead
Is it possible to determine which level/key of a nested dict that contained None, causing 'NoneType' object is not subscriptable?
How does Intellij code inspection decide on selectors from .css files?
Android studio code inspection shell script for integration in CI pipeline
ESLint: Cannot start language service process / problem with HLS .ts extension
Define a classes possible properties
How do I check ReSharper code inspections of Unity Project via a command line?
Trouble using std::make_unique with member variable of class
Contstraint stream breaks when switching from OptaPlanner 7.46.0 to 8.0.0
jcrop-holder is duplicated on my live page
QUESTION
Expected type 'Type[Add | Sub | Mult | Div | Pow | BitXor | USub]', got 'Type[operator]' instead
Asked 2022-Mar-05 at 00:221# Taken out of context for MVCE
2
3import ast
4import operator as op
5
6OPERATORS = {
7 ast.Add: op.add,
8 ast.Sub: op.sub,
9 ast.Mult: op.mul,
10 ast.Div: op.truediv,
11 ast.Pow: op.pow,
12 ast.BitXor: op.xor,
13 ast.USub: op.neg
14}
15
16def eval_expr(expr):
17
18 return eval_(ast.parse(expr, mode='eval').body)
19
20def eval_(node):
21 if isinstance(node, ast.Num): # <number>
22 value = node.n
23 elif isinstance(node, ast.BinOp): # <left> <operator> <right>
24 value = OPERATORS[type(node.op)](eval_(node.left), eval_(node.right))
25 elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
26 value = OPERATORS[type(node.op)](eval_(node.operand))
27 else:
28 raise TypeError(node)
29
30 return value
31
32x = eval_expr("1 + 2")
33print(x)
34
PyCharm code inspection highlights the instances of type(node.op)
as problematic:
1# Taken out of context for MVCE
2
3import ast
4import operator as op
5
6OPERATORS = {
7 ast.Add: op.add,
8 ast.Sub: op.sub,
9 ast.Mult: op.mul,
10 ast.Div: op.truediv,
11 ast.Pow: op.pow,
12 ast.BitXor: op.xor,
13 ast.USub: op.neg
14}
15
16def eval_expr(expr):
17
18 return eval_(ast.parse(expr, mode='eval').body)
19
20def eval_(node):
21 if isinstance(node, ast.Num): # <number>
22 value = node.n
23 elif isinstance(node, ast.BinOp): # <left> <operator> <right>
24 value = OPERATORS[type(node.op)](eval_(node.left), eval_(node.right))
25 elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
26 value = OPERATORS[type(node.op)](eval_(node.operand))
27 else:
28 raise TypeError(node)
29
30 return value
31
32x = eval_expr("1 + 2")
33print(x)
34Expected type 'Type[Add | Sub | Mult | Div | Pow | BitXor | USub]' (matched generic type '_KT'), got 'Type[operator]' instead
35Expected type 'Type[Add | Sub | Mult | Div | Pow | BitXor | USub]' (matched generic type '_KT'), got 'Type[unaryop]' instead
36
The class seems to function just fine, but my OCD wants to know how this could be refactored to avoid the inspection warnings. Or is this a PyCharm inspection gremlin?
ANSWER
Answered 2022-Mar-05 at 00:22The type checker is warning you that your dictionary that maps AST node types for operators to their implementations is incomplete. The type checker knows all of the possible types of node.op
(which it seems to be describing as subtypes of the ast.operator
and ast.unaryop
parent types), and has noticed that your dictionary doesn't handle them all.
Since there are operators that you haven't included, it's possible for a parsable expression (like, say "2 << 5"
which does a left shift, or "~31"
which does a bitwise inversion) to fail to be handled by your code.
While I don't use PyCharm and thus can't test it for myself, you can probably satisfy its type checker by adding some error handling to your code, so that operator types you don't support will still be dealt with appropriately, rather than causing an uncaught exception (such as a KeyError
from the dictionary) to leak out. For instance, you could use OPERATORS.get(type(node.op))
and then test for None
before calling the result. If the operator type isn't in the dictionary, you'd raise an exception of your own.
QUESTION
Is it possible to determine which level/key of a nested dict that contained None, causing 'NoneType' object is not subscriptable?
Asked 2022-Jan-29 at 11:08The users of my framework (who may or may not be well versed in Python) write code that navigates a dict (that originally came from a json response from some API).
Sometimes they make a mistake, or sometimes the API returns data with some value missing, and they get the dreaded 'NoneType' object is not subscriptable
How can I make it clear at what level the error occured? (what key returned None)
1def user_code(some_dict):
2 # I can't modify this code, it is written by the user
3 something = some_dict["a"]["b"]["c"]
4
5# I don't control the contents of this.
6data_from_api = '{"a": {"b": None}}'
7
8# framework code, I control this
9try:
10 user_code(json.loads(data_from_api))
11except TypeError as e:
12 # I'd like to print an error message containing "a","b" here
13
I can overload/alter the dict implementation if necessary, but I don't want to do source code inspection.
There may already be answers to this question (or maybe it is impossible), but it is terribly hard to find among all the basic Why am I getting 'NoneType' object is not subscriptable? questions. My apologies if this is a duplicate.
Edit: @2e0byo's answer is the most correct to my original question, but I did find autoviv to provice a nice solution to my "real" underlying issue (allowing users to easily navigate a dict that sometimes doesnt have all the expected data), so I chose that approach instead. The only real down side with it is if someone relies on some_dict["a"]["b"]["c"]
to throw an exception. My solution is something like this:
1def user_code(some_dict):
2 # I can't modify this code, it is written by the user
3 something = some_dict["a"]["b"]["c"]
4
5# I don't control the contents of this.
6data_from_api = '{"a": {"b": None}}'
7
8# framework code, I control this
9try:
10 user_code(json.loads(data_from_api))
11except TypeError as e:
12 # I'd like to print an error message containing "a","b" here
13def user_code(some_dict):
14 # this doesnt crash anymore, and instead sets something to None
15 something = some_dict["a"]["b"]["c"]
16
17# I don't control the contents of this.
18data_from_api = '{"a": {"b": None}}'
19
20# framework code, I control this
21user_code(autoviv.loads(data_from_api))
22
ANSWER
Answered 2022-Jan-17 at 12:57Here is one approach to this problem: make your code return a custom Result()
object wrapping each object. (This approach could be generalised to a monad approach with .left()
and .right()
, but I didn't go there as I don't see that pattern very often (in my admittedly small experience!).)
Firstly the custom Result()
object:
1def user_code(some_dict):
2 # I can't modify this code, it is written by the user
3 something = some_dict["a"]["b"]["c"]
4
5# I don't control the contents of this.
6data_from_api = '{"a": {"b": None}}'
7
8# framework code, I control this
9try:
10 user_code(json.loads(data_from_api))
11except TypeError as e:
12 # I'd like to print an error message containing "a","b" here
13def user_code(some_dict):
14 # this doesnt crash anymore, and instead sets something to None
15 something = some_dict["a"]["b"]["c"]
16
17# I don't control the contents of this.
18data_from_api = '{"a": {"b": None}}'
19
20# framework code, I control this
21user_code(autoviv.loads(data_from_api))
22class Result:
23 def __init__(self, val):
24 self._val = val
25
26 def __getitem__(self, k):
27 try:
28 return self._val[k]
29 except KeyError:
30 raise Exception("No such key")
31 except TypeError:
32 raise Exception(
33 "Result is None. This probably indicates an error in your code."
34 )
35
36 def __getattr__(self, a):
37 try:
38 return self._val.a
39 except AttributeError:
40 if self._val is None:
41 raise Exception(
42 "Result is None. This probably indicates an error in your code."
43 )
44 else:
45 raise Exception(
46 f"No such attribute for value of type {type(self._val)}, valid attributes are {dir(self._val)}"
47 )
48
49 @property
50 def val(self):
51 return self._val
52
Of course, there's a lot of room for improvement here (e.g. __repr__()
and you might want to modify the error messages).
In action:
1def user_code(some_dict):
2 # I can't modify this code, it is written by the user
3 something = some_dict["a"]["b"]["c"]
4
5# I don't control the contents of this.
6data_from_api = '{"a": {"b": None}}'
7
8# framework code, I control this
9try:
10 user_code(json.loads(data_from_api))
11except TypeError as e:
12 # I'd like to print an error message containing "a","b" here
13def user_code(some_dict):
14 # this doesnt crash anymore, and instead sets something to None
15 something = some_dict["a"]["b"]["c"]
16
17# I don't control the contents of this.
18data_from_api = '{"a": {"b": None}}'
19
20# framework code, I control this
21user_code(autoviv.loads(data_from_api))
22class Result:
23 def __init__(self, val):
24 self._val = val
25
26 def __getitem__(self, k):
27 try:
28 return self._val[k]
29 except KeyError:
30 raise Exception("No such key")
31 except TypeError:
32 raise Exception(
33 "Result is None. This probably indicates an error in your code."
34 )
35
36 def __getattr__(self, a):
37 try:
38 return self._val.a
39 except AttributeError:
40 if self._val is None:
41 raise Exception(
42 "Result is None. This probably indicates an error in your code."
43 )
44 else:
45 raise Exception(
46 f"No such attribute for value of type {type(self._val)}, valid attributes are {dir(self._val)}"
47 )
48
49 @property
50 def val(self):
51 return self._val
52def to_result(thing):
53 if isinstance(thing, dict):
54 return Result({k: to_result(v) for k, v in thing.items()})
55 else:
56 return Result(thing)
57
58d = {"a": {"b": None}}
59r_dd = to_result(d)
60r_dd["a"] # Returns a Result object
61r_dd["a"]["b"] # Returns a Result object
62r_dd["a"]["c"] # Raises a helpful error
63r_dd["a"]["b"]["c"] # Raises a helpful error
64r_dd["a"]["b"].val # None
65r_dd["a"]["b"].nosuchattr # Raises a helpful error
66
If I'm going to serve up a custom object I want my users to know it's a custom object. So we have a wrapper class, and we tell users that the paradim is 'get at the object, and then use .val to get the result'. Handling the wrong .val is their code's problem (so if .val
is None, they have to handle that). But handling a problem in the data structure is sort of our problem, so we hand them a custom class with helpful messages rather than anything else.
As currently implemented it's easy to get one above in the error msg (for dict lookups). If you want to get more than that you need to keep a reference up the hierarchy in the Result---which might be better written with Result as something other than just a wrapper.
I'm not sure if this is the kind of solution you were looking for, but it might be a step in the right direction.
QUESTION
How does Intellij code inspection decide on selectors from .css files?
Asked 2022-Jan-21 at 10:17I have a css
file in which there's a selector for class App-logo
1.App-logo {
2 animation: App-logo-spin infinite 20s linear;
3 height: 75px;
4}
5
The file is in resources/public
directory.
In the resources
directory, there's a file called testform.vtl
(a velocity file), in which the following lines appear:
1.App-logo {
2 animation: App-logo-spin infinite 20s linear;
3 height: 75px;
4}
5 <div class="App-header" >
6 <img src="favicon.png" class="App-logo pull-left" alt="logo" />
7 <h2>Data Insight - Known Issues Console </h2>
8 </div>
9
When I run code inspection in Intellij, it gives me the warning Selector app-logo is never used
. Why is this? Is there a configuration that I can use in Intellij to cause it to look at these vtl files (if this is actually the problem)?
ANSWER
Answered 2022-Jan-21 at 10:17The IDE only looks for CSS selector usages in stylesheets and HTML files/fragments; it won't inspect plain text files and files of unknown type. I've just checked - CSS usages are correctly found in Velocity templates:
Make sure to add *.vtl
pattern to Velocity Template file type in Settings | Editor | File Types
QUESTION
Android studio code inspection shell script for integration in CI pipeline
Asked 2021-Oct-22 at 10:17I am trying to integrate dead code analysis for my android app to improve code quality. I found out the code inspection option that android studio provides out of the box which is giving me an extensive report of unused code and suggested improvements.
I used the Analyze -> inspect code option
I get the results in studio as follows:
This is very useful but I want to integrate this code analysis into my CI pipeline so that I can track and trend the warnings that are reported.
I found out a blog that said I can use the inpsect.sh file that comes with the Android Studio package for the same purpose. The syntax of the command is as follows:
1sh inspect.sh <project> <inspection-profile> <output> [<options>]
2
I tried to run this command by passing the appropriate parameters given below:
1sh inspect.sh <project> <inspection-profile> <output> [<options>]
2sh inspect.sh Users/user1/Documents/androidProject /Users/user1/Documents/androidProject/app/src/InspectionProfile.xml /Users/user1/Documents/inspectionResults -v2 -d /Users/user1/Documents/androidProject/app/src
3
but whenever I try to run this shell script with the required params I am getting the following error:
1sh inspect.sh <project> <inspection-profile> <output> [<options>]
2sh inspect.sh Users/user1/Documents/androidProject /Users/user1/Documents/androidProject/app/src/InspectionProfile.xml /Users/user1/Documents/inspectionResults -v2 -d /Users/user1/Documents/androidProject/app/src
3inspect.sh: line 9: exec: /Applications/Android Studio.app/Contents/bin/inspect.sh/../MacOS/studio: cannot execute: Not a directory
4
Spent lot of time but no luck. What am i missing here?
ANSWER
Answered 2021-Oct-21 at 10:00It's because you didn't specify a parameter for the -d
option.
-d <Specify the full path to the subdirectory if you don't want to inspect the whole project.>
It should be like this:
1sh inspect.sh <project> <inspection-profile> <output> [<options>]
2sh inspect.sh Users/user1/Documents/androidProject /Users/user1/Documents/androidProject/app/src/InspectionProfile.xml /Users/user1/Documents/inspectionResults -v2 -d /Users/user1/Documents/androidProject/app/src
3inspect.sh: line 9: exec: /Applications/Android Studio.app/Contents/bin/inspect.sh/../MacOS/studio: cannot execute: Not a directory
4inspect.sh 'Users/user1/Documents/androidProject' '/Users/user1/Documents/androidProject/app/src/InspectionProfile.xml' '/Users/user1/Documents/inspectionResults' -v2 -d '/Users/user1/Documents/androidProject/app/src'
5
QUESTION
ESLint: Cannot start language service process / problem with HLS .ts extension
Asked 2021-Sep-22 at 20:21IMPORTANT: Please see UPDATE EDIT below which provides vital info
I keep getting this error showing in WebStorm 2021.2.2 (and other recent version) when using Angular:
ESLint: Cannot start language service process
See screenshot below
All .ts files report a similar error:
ESLint: Can not get result from language service
I tried to reproduce the problem by creating a new Angular project as follows:
1ng new video-and-event-listeners-test --style=scss --routing=true
2cd video-and-event-listeners-test/
3ng add @angular-eslint/schematics --skip-confirmation
4
Initially everything worked OK but then the error returned and I cannot get rid of it. I have this error in every project (my projects all contain HLS files - see edit below). The ng lint
command just hangs. WebStorm just fails when you run a code inspection. Any ideas how to fix this please (without just disabling eslint)? Working without eslint is like digging a hole without a spade :(
Other versions of relevant software:
1ng new video-and-event-listeners-test --style=scss --routing=true
2cd video-and-event-listeners-test/
3ng add @angular-eslint/schematics --skip-confirmation
4Node.js version 14.17.3
5@angular/cli@12.2.6 (global install)
6Angular 12.2.0
7eslint 7.26.0 (installed by the above `ng add` command)
8
UPDATE EDIT:
OK I finally have a lead to go on! I have a directory as follows:
/src/assets/test-videos
This folder contains a bunch of HLS streaming videos. The HLS video chunks / segments have a .ts extension. A .ts extension is standard for HLS chunks but they seem to be causing ESLint to fail (since ESLint is linting .ts files). If I delete the entire folder, ESLint starts working!!! When I restore the folder, ESLint stops working.
So I tried to put the folder on ignore by adding a .eslintignore file in my project root with the contents:
1ng new video-and-event-listeners-test --style=scss --routing=true
2cd video-and-event-listeners-test/
3ng add @angular-eslint/schematics --skip-confirmation
4Node.js version 14.17.3
5@angular/cli@12.2.6 (global install)
6Angular 12.2.0
7eslint 7.26.0 (installed by the above `ng add` command)
8src/assets/test-videos/**/*
9/src/assets/test-videos/**/*
10./src/assets/test-videos/**/*
11
12src/assets/test-videos/*
13/src/assets/test-videos/*
14./src/assets/test-videos/*
15
16src/assets/test-videos/
17/src/assets/test-videos/
18./src/assets/test-videos/
19
20src/assets/test-videos
21/src/assets/test-videos
22./src/assets/test-videos
23
24test-videos/**/*
25
Also I've added the following entry to .eslintrc.json
1ng new video-and-event-listeners-test --style=scss --routing=true
2cd video-and-event-listeners-test/
3ng add @angular-eslint/schematics --skip-confirmation
4Node.js version 14.17.3
5@angular/cli@12.2.6 (global install)
6Angular 12.2.0
7eslint 7.26.0 (installed by the above `ng add` command)
8src/assets/test-videos/**/*
9/src/assets/test-videos/**/*
10./src/assets/test-videos/**/*
11
12src/assets/test-videos/*
13/src/assets/test-videos/*
14./src/assets/test-videos/*
15
16src/assets/test-videos/
17/src/assets/test-videos/
18./src/assets/test-videos/
19
20src/assets/test-videos
21/src/assets/test-videos
22./src/assets/test-videos
23
24test-videos/**/*
25{
26 "root": true,
27 "ignorePatterns": [
28 "projects/**/*",
29 "src/assets/test-videos/**/*"
30 ],
31 etc
32}
33
But still no cigar. If the problem directory is not deleted ESLint just will not work! I suppose I could rename all the HLS files to use a non-standard extension but I'd rather not. Any ideas? Many thanks
ANSWER
Answered 2021-Sep-22 at 14:32Looks as if the settings in .eslintignore
only affect errors reporting, whereas the settings in tsconfig.json
affect parsing. Adding "exclude": ["src/assets/test-videos"]
to the root tsconfig.json
should help.
I've verified that it works the same when running eslint in terminal with eslint src/**/*.*
- if the files are not excluded in tsconfig.json
, ESLint runs out of memory
QUESTION
Define a classes possible properties
Asked 2021-Sep-20 at 13:10I don't want to turn off an code inspections, but is there a way I can define what class properties could be defined, so when using methods within the class I'm not getting Unresolved variable
warning?
I would use TypeScript however I can't do that right now. Is there another way? There's many properties that can be set or not set.
I can remove this within the constructor by defining what value can contain:
ANSWER
Answered 2021-Sep-20 at 13:01Define class properties and write jsdoc like this:
1class Base {
2 /**
3 * @type {boolean}
4 */
5
6 disableReset;
7
8 /**
9 * @param {boolean} disableReset
10 */
11 constructor(disableReset) {
12 this.disableReset = disableReset;
13 }
14 reset() {
15 if (this.disableReset) {
16 // do stuff
17 }
18 }
19}
20
QUESTION
How do I check ReSharper code inspections of Unity Project via a command line?
Asked 2021-Aug-10 at 13:04Given:
- Unity project
- ReSharper is used to check inspections (IDE Rider)
I want to:
- Run code inspections on a CI / CD system (TeamCity)
ANSWER
Answered 2021-Aug-10 at 13:04To run inspections from the command line, you need:
- Download ReSharper command line tools
- Download Unity plugin for ReSharper
- Put the plugin in the root of the ReSharper folder
- Run the tool:
InspectCode.exe YourSolution.sln -o=<PathToOutputFile>
More options - Get a beautiful XML report
TeamCity has a special runner type to run such checks: Inspections (ReSharper)
In the R# CLT Plugins
field, you will need to specify the Unity plugin, for example: Download JetBrains.Unity/2021.2.0.129
If the .sln
file is not generated at the previous steps of building your project, you can generate it with running Unity with the parameter -executeMethod UnityEditor.SyncVS.SyncSolution
QUESTION
Trouble using std::make_unique with member variable of class
Asked 2021-Aug-05 at 20:03I have not used std::make_unique
before, and code inspection encouraged me to do it.
If I use this, it does not display errors:
1auto x = make_unique<CChristianLifeMinistryHtmlView>();
2
But when I try it with my class member variable CChristianLifeMinistryHtmlView *m_pHtmlPreview
it does not like it:
1auto x = make_unique<CChristianLifeMinistryHtmlView>();
2m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();
3
How do I use std::make_unique
with a member variable of the class?
ANSWER
Answered 2021-Aug-05 at 19:02Your issue is nothing to do with the class member, rather its type!
std::make_unique()
returns std::unique_ptr
for the template type T
(i.e. std::unique_ptr
of an instance of type T
)
1auto x = make_unique<CChristianLifeMinistryHtmlView>();
2m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();
3template< class T, class... Args >
4unique_ptr<T> make_unique( Args&&... args );
5^^^^^^^^^^^^^^
6
The member
1auto x = make_unique<CChristianLifeMinistryHtmlView>();
2m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();
3template< class T, class... Args >
4unique_ptr<T> make_unique( Args&&... args );
5^^^^^^^^^^^^^^
6CChristianLifeMinistryHtmlView *m_pHtmlPreview;
7
is a pointer to a CChristianLifeMinistryHtmlView
, not a std::unique_ptr
. Hence, the type mismatch.
How do I use
make_unique
with a member variable of the class?
Therefore, you need to use std::unique_ptr<CChristianLifeMinistryHtmlView>
as the type of the m_pHtmlPreview
member:
1auto x = make_unique<CChristianLifeMinistryHtmlView>();
2m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();
3template< class T, class... Args >
4unique_ptr<T> make_unique( Args&&... args );
5^^^^^^^^^^^^^^
6CChristianLifeMinistryHtmlView *m_pHtmlPreview;
7std::unique_ptr<CChristianLifeMinistryHtmlView> m_pHtmlPreview;
8...
9m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();
10
If it is a long typing, a type alias wouldn't be a bad idea:
1auto x = make_unique<CChristianLifeMinistryHtmlView>();
2m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();
3template< class T, class... Args >
4unique_ptr<T> make_unique( Args&&... args );
5^^^^^^^^^^^^^^
6CChristianLifeMinistryHtmlView *m_pHtmlPreview;
7std::unique_ptr<CChristianLifeMinistryHtmlView> m_pHtmlPreview;
8...
9m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();
10using UniqueCLMHView = std::unique_ptr<CChristianLifeMinistryHtmlView>;
11UniqueCLMHView m_pHtmlPreview;
12...
13m_pHtmlPreview = std::make_unique<CChristianLifeMinistryHtmlView>();
14
QUESTION
Contstraint stream breaks when switching from OptaPlanner 7.46.0 to 8.0.0
Asked 2020-Dec-02 at 21:02I have a constraint that crashes in the latest OptaPlanner 8.0.0, but used to work fine on 7.46.0.
As expected, IntelliJ's code inspection (and the debugger) shows that after the first join, the stream is a TriConstraintStream
. The runtime class makes more sense to me than the class OptaPlanner is trying to cast to.
When leaving out the last groupBy
the error goes away, so that clause seems to cause the issue.
Did something change in the way join and groupby worked?
It seems that the underlying OptaPlanner code was refactored for 8.0.0, so I have trouble seeing what exactly changed in OptaPlanner.
Should I add something to ensure that a TriJoin is used instead of a BiJoin?
I could not find any relevant notes in the migration documentation.
1protected Constraint preventProductionShortage(ConstraintFactory factory) {
2 return factory.from(Demand.class)
3 .groupBy(Demand::getSKU,
4 Demand::getWeekNumber
5 )//BiConstraintStream
6 .join(Demand.class,
7 equal((sku, weekNumber)-> sku, Demand::getSKU),
8 greaterThanOrEqual((sku, weekNumber)-> weekNumber, Demand::getWeekNumber)//TriConstraintStream
9 )
10 .groupBy((sku, weekNumber, totalDemand) -> sku,
11 (sku, weekNumber, totalDemand) -> weekNumber,
12 sum((sku, weekNumber, totalDemand) -> totalDemand.getOrderQuantity())
13 )//TriConstraintStream
14 .penalize("Penalty", HardMediumSoftScore.ONE_MEDIUM,
15 (sku_weekNumber, demandQty, productionQty) -> 1);
16}
17
Stack trace:
1protected Constraint preventProductionShortage(ConstraintFactory factory) {
2 return factory.from(Demand.class)
3 .groupBy(Demand::getSKU,
4 Demand::getWeekNumber
5 )//BiConstraintStream
6 .join(Demand.class,
7 equal((sku, weekNumber)-> sku, Demand::getSKU),
8 greaterThanOrEqual((sku, weekNumber)-> weekNumber, Demand::getWeekNumber)//TriConstraintStream
9 )
10 .groupBy((sku, weekNumber, totalDemand) -> sku,
11 (sku, weekNumber, totalDemand) -> weekNumber,
12 sum((sku, weekNumber, totalDemand) -> totalDemand.getOrderQuantity())
13 )//TriConstraintStream
14 .penalize("Penalty", HardMediumSoftScore.ONE_MEDIUM,
15 (sku_weekNumber, demandQty, productionQty) -> 1);
16}
17java.lang.ClassCastException: class org.optaplanner.core.impl.score.stream.tri.CompositeTriJoiner cannot be cast to class org.optaplanner.core.impl.score.stream.bi.AbstractBiJoiner (org.optaplanner.core.impl.score.stream.tri.CompositeTriJoiner and org.optaplanner.core.impl.score.stream.bi.AbstractBiJoiner are in unnamed module of loader 'app')
18
19 at org.optaplanner.core.impl.score.stream.drools.common.rules.BiJoinMutator.<init>(BiJoinMutator.java:40)
20 at org.optaplanner.core.impl.score.stream.drools.common.rules.UniRuleAssembler.join(UniRuleAssembler.java:70)
21 at org.optaplanner.core.impl.score.stream.drools.common.rules.AbstractRuleAssembler.join(AbstractRuleAssembler.java:179)
22 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintSubTree.getRuleAssembler(ConstraintSubTree.java:94)
23 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintSubTree.getRuleAssembler(ConstraintSubTree.java:89)
24 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.generateRule(ConstraintGraph.java:431)
25 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.lambda$generateRule$57(ConstraintGraph.java:423)
26 at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
27 at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
28 at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
29 at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
30 at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
31 at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
32 at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
33 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.generateRule(ConstraintGraph.java:424)
34 at org.optaplanner.core.impl.score.stream.drools.DroolsConstraintFactory.buildSessionFactory(DroolsConstraintFactory.java:101)
35 at org.optaplanner.core.impl.score.director.stream.ConstraintStreamScoreDirectorFactory.<init>(ConstraintStreamScoreDirectorFactory.java:77)
36 at org.optaplanner.test.impl.score.stream.DefaultConstraintVerifier.verifyThat(DefaultConstraintVerifier.java:63)
37 at org.optaplanner.test.impl.score.stream.DefaultConstraintVerifier.verifyThat(DefaultConstraintVerifier.java:32)
38 at com.ohly.planner.constraints.ConstraintsTest.weekShortageSingleSKU(ConstraintsTest.java:61)
39 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
40 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
41 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
42 at java.base/java.lang.reflect.Method.invoke(Method.java:564)
43 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
44 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
45 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
46 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
47 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
48 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
49 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
50 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
51 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
52 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
53 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
54 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
55 at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
56 at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
57 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
58 at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
59 at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
60 at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
61
62
63Process finished with exit code -1
64
[edit] For completeness, the new function as suggested by Lukáš Petrovický
1protected Constraint preventProductionShortage(ConstraintFactory factory) {
2 return factory.from(Demand.class)
3 .groupBy(Demand::getSKU,
4 Demand::getWeekNumber
5 )//BiConstraintStream
6 .join(Demand.class,
7 equal((sku, weekNumber)-> sku, Demand::getSKU),
8 greaterThanOrEqual((sku, weekNumber)-> weekNumber, Demand::getWeekNumber)//TriConstraintStream
9 )
10 .groupBy((sku, weekNumber, totalDemand) -> sku,
11 (sku, weekNumber, totalDemand) -> weekNumber,
12 sum((sku, weekNumber, totalDemand) -> totalDemand.getOrderQuantity())
13 )//TriConstraintStream
14 .penalize("Penalty", HardMediumSoftScore.ONE_MEDIUM,
15 (sku_weekNumber, demandQty, productionQty) -> 1);
16}
17java.lang.ClassCastException: class org.optaplanner.core.impl.score.stream.tri.CompositeTriJoiner cannot be cast to class org.optaplanner.core.impl.score.stream.bi.AbstractBiJoiner (org.optaplanner.core.impl.score.stream.tri.CompositeTriJoiner and org.optaplanner.core.impl.score.stream.bi.AbstractBiJoiner are in unnamed module of loader 'app')
18
19 at org.optaplanner.core.impl.score.stream.drools.common.rules.BiJoinMutator.<init>(BiJoinMutator.java:40)
20 at org.optaplanner.core.impl.score.stream.drools.common.rules.UniRuleAssembler.join(UniRuleAssembler.java:70)
21 at org.optaplanner.core.impl.score.stream.drools.common.rules.AbstractRuleAssembler.join(AbstractRuleAssembler.java:179)
22 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintSubTree.getRuleAssembler(ConstraintSubTree.java:94)
23 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintSubTree.getRuleAssembler(ConstraintSubTree.java:89)
24 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.generateRule(ConstraintGraph.java:431)
25 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.lambda$generateRule$57(ConstraintGraph.java:423)
26 at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
27 at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
28 at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
29 at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
30 at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
31 at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
32 at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
33 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.generateRule(ConstraintGraph.java:424)
34 at org.optaplanner.core.impl.score.stream.drools.DroolsConstraintFactory.buildSessionFactory(DroolsConstraintFactory.java:101)
35 at org.optaplanner.core.impl.score.director.stream.ConstraintStreamScoreDirectorFactory.<init>(ConstraintStreamScoreDirectorFactory.java:77)
36 at org.optaplanner.test.impl.score.stream.DefaultConstraintVerifier.verifyThat(DefaultConstraintVerifier.java:63)
37 at org.optaplanner.test.impl.score.stream.DefaultConstraintVerifier.verifyThat(DefaultConstraintVerifier.java:32)
38 at com.ohly.planner.constraints.ConstraintsTest.weekShortageSingleSKU(ConstraintsTest.java:61)
39 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
40 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
41 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
42 at java.base/java.lang.reflect.Method.invoke(Method.java:564)
43 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
44 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
45 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
46 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
47 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
48 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
49 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
50 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
51 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
52 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
53 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
54 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
55 at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
56 at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
57 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
58 at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
59 at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
60 at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
61
62
63Process finished with exit code -1
64 protected Constraint preventProductionShortage(ConstraintFactory factory) {
65 return factory.from(Demand.class)
66 .join(Demand.class,
67 equal(Demand::getSKU),
68 greaterThanOrEqual(demand -> demand.getWeekNumber()))
69 .groupBy((d, d2) -> d.getSKU(),
70 (d, d2) -> d.getWeekNumber(),
71 sum((d,d2) -> d2.getOrderQuantity())
72 )
73 ...
74
[/edit]
ANSWER
Answered 2020-Dec-02 at 19:53This was an unfortunate bug not caught by the existing test coverage. The fix is aimed at OptaPlanner 8.0.1, incl. test coverage improvement.
That said, I would argue that the constraint is not very efficient. Unless I'm missing some key implications, the following is semantically very similar, yet much faster:
1protected Constraint preventProductionShortage(ConstraintFactory factory) {
2 return factory.from(Demand.class)
3 .groupBy(Demand::getSKU,
4 Demand::getWeekNumber
5 )//BiConstraintStream
6 .join(Demand.class,
7 equal((sku, weekNumber)-> sku, Demand::getSKU),
8 greaterThanOrEqual((sku, weekNumber)-> weekNumber, Demand::getWeekNumber)//TriConstraintStream
9 )
10 .groupBy((sku, weekNumber, totalDemand) -> sku,
11 (sku, weekNumber, totalDemand) -> weekNumber,
12 sum((sku, weekNumber, totalDemand) -> totalDemand.getOrderQuantity())
13 )//TriConstraintStream
14 .penalize("Penalty", HardMediumSoftScore.ONE_MEDIUM,
15 (sku_weekNumber, demandQty, productionQty) -> 1);
16}
17java.lang.ClassCastException: class org.optaplanner.core.impl.score.stream.tri.CompositeTriJoiner cannot be cast to class org.optaplanner.core.impl.score.stream.bi.AbstractBiJoiner (org.optaplanner.core.impl.score.stream.tri.CompositeTriJoiner and org.optaplanner.core.impl.score.stream.bi.AbstractBiJoiner are in unnamed module of loader 'app')
18
19 at org.optaplanner.core.impl.score.stream.drools.common.rules.BiJoinMutator.<init>(BiJoinMutator.java:40)
20 at org.optaplanner.core.impl.score.stream.drools.common.rules.UniRuleAssembler.join(UniRuleAssembler.java:70)
21 at org.optaplanner.core.impl.score.stream.drools.common.rules.AbstractRuleAssembler.join(AbstractRuleAssembler.java:179)
22 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintSubTree.getRuleAssembler(ConstraintSubTree.java:94)
23 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintSubTree.getRuleAssembler(ConstraintSubTree.java:89)
24 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.generateRule(ConstraintGraph.java:431)
25 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.lambda$generateRule$57(ConstraintGraph.java:423)
26 at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
27 at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
28 at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
29 at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
30 at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
31 at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
32 at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
33 at org.optaplanner.core.impl.score.stream.drools.common.ConstraintGraph.generateRule(ConstraintGraph.java:424)
34 at org.optaplanner.core.impl.score.stream.drools.DroolsConstraintFactory.buildSessionFactory(DroolsConstraintFactory.java:101)
35 at org.optaplanner.core.impl.score.director.stream.ConstraintStreamScoreDirectorFactory.<init>(ConstraintStreamScoreDirectorFactory.java:77)
36 at org.optaplanner.test.impl.score.stream.DefaultConstraintVerifier.verifyThat(DefaultConstraintVerifier.java:63)
37 at org.optaplanner.test.impl.score.stream.DefaultConstraintVerifier.verifyThat(DefaultConstraintVerifier.java:32)
38 at com.ohly.planner.constraints.ConstraintsTest.weekShortageSingleSKU(ConstraintsTest.java:61)
39 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
40 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
41 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
42 at java.base/java.lang.reflect.Method.invoke(Method.java:564)
43 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
44 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
45 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
46 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
47 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
48 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
49 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
50 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
51 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
52 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
53 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
54 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
55 at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
56 at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
57 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
58 at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
59 at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
60 at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
61
62
63Process finished with exit code -1
64 protected Constraint preventProductionShortage(ConstraintFactory factory) {
65 return factory.from(Demand.class)
66 .join(Demand.class,
67 equal(Demand::getSKU),
68 greaterThanOrEqual(demand -> demand.getWeekNumber()))
69 .groupBy((d, d2) -> d.getSKU(),
70 (d, d2) -> d.getWeekNumber(),
71 sum((d,d2) -> d2.getOrderQuantity())
72 )
73 ...
74protected Constraint preventProductionShortage(ConstraintFactory factory) {
75 return factory.from(Demand.class)
76 .join(Demand.class,
77 equal(Demand::getSKU),
78 greaterThanOrEqual(demand -> demand.getWeekNumber()))
79 .groupBy(..., ..., sum((demand, demand2) -> ...))
80 .penalize("Penalty", HardMediumSoftScore.ONE_MEDIUM);
81
}
Note how I eliminated the first use of groupBy()
. There may be some difference though in how many tuples are penalized this way, which may or may not be what you want. Feel free to open another question on that.
QUESTION
jcrop-holder is duplicated on my live page
Asked 2020-Oct-25 at 14:39I am trying to create a page on my site that uses Jcrop
to edit and then save the edited images.
My issue is that when I load the page on Chrome or Microsoft Edge the jcrop-holder
is duplicated and the image appears on the browser twice.
I cannot work out what is the issue, any help would be much appreciated!
Bellow is my code:
1<!DOCTYPE html>
2<html lang="en">
3
4<head>
5 <title>Aspect Ratio with Preview Pane | Jcrop Demo</title>
6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
7
8<script src="js/jquery.min.js"></script>
9<script src="js/jquery.Jcrop.min.js"></script>
10<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
11
12<!-- Bootstrap core CSS -->
13<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
14<!-- Custom styles for this template -->
15<link href="css/heroic-features.css" rel="stylesheet">
16
17<!-- Bootstrap core CSS -->
18<link href="vendor/bootstrap[enter image description here][1]/css/bootstrap.min.css" rel="stylesheet">
19
20<!-- Custom styles for this template -->
21<link href="css/heroic-features.css" rel="stylesheet">
22
23<style type="text/css">
24
25/* Apply these styles only when #preview-pane has
26 been placed within the Jcrop widget */
27.jcrop-holder #preview-pane {
28 display: block;
29 position: absolute;
30 z-index: 2000;
31 top: 10px;
32 right: -280px;
33 padding: 6px;
34 border: 1px rgba(0,0,0,.4) solid;
35 background-color: white;
36
37 -webkit-border-radius: 6px;
38 -moz-border-radius: 6px;
39 border-radius: 6px;
40
41 -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
42 -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
43 box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
44}
45
46/* The Javascript code will set the aspect ratio of the crop
47 area based on the size of the thumbnail preview,
48 specified here */
49#preview-pane .preview-container {
50 width: 250px;
51 height: 170px;
52 overflow: hidden;
53}
54
55</style>
56
57
58<script type="text/javascript">
59
60 jQuery(function($){
61
62 // Create variables (in this scope) to hold the API and image size
63 var jcrop_api,
64 boundx,
65 boundy,
66
67 // Grab some information about the preview pane
68 $preview = $('#preview-pane'),
69 $pcnt = $('#preview-pane .preview-container'),
70 $pimg = $('#preview-pane .preview-container img'),
71
72 xsize = $pcnt.width(),
73 ysize = $pcnt.height();
74
75 console.log('init',[xsize,ysize]);
76 $('#target').Jcrop({
77 onChange: updatePreview,
78 onSelect: updatePreview,
79 aspectRatio: xsize / ysize
80 },function(){
81 // Use the API to get the real image size
82 var bounds = this.getBounds();
83 boundx = bounds[0];
84 boundy = bounds[1];
85 // Store the API in the jcrop_api variable
86 jcrop_api = this;
87
88 // Move the preview into the jcrop container for css positioning
89 $preview.appendTo(jcrop_api.ui.holder);
90 });
91
92 function updatePreview(c)
93 {
94 if (parseInt(c.w) > 0)
95 {
96 var rx = xsize / c.w;
97 var ry = ysize / c.h;
98
99 $pimg.css({
100 width: Math.round(rx * boundx) + 'px',
101 height: Math.round(ry * boundy) + 'px',
102 marginLeft: '-' + Math.round(rx * c.x) + 'px',
103 marginTop: '-' + Math.round(ry * c.y) + 'px'
104 });
105 }
106 };
107
108 });
109
110</script>
111
112</head>
113
114
115
116<body style="zoom: 1;">
117<div class="container">
118<div class="row">
119<div class="span12">
120<div class="jc-demo-box">
121 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" id="target" style="display: none; visibility: hidden; width: 602px; height: 400px;">
122
123
124 <div class="jcrop-holder" style="width: 602px; height: 400px; position: relative; background-color: black;">
125
126 <div style="position: absolute; z-index: 600;">
127
128 <div style="width: 100%; height: 100%; z-index: 310; position: absolute; overflow: hidden;">
129
130 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" style="border: none; visibility: visible; margin: 0px; padding: 0px; position: absolute; top: 0px; left: 0px; width: 602px; height: 400px;">
131
132 <div class="jcrop-hline" style="position: absolute; opacity: 0.4;"> </div>
133
134 <div class="jcrop-hline bottom" style="position: absolute; opacity: 0.4;"> </div>
135
136 <div class="jcrop-vline right" style="position: absolute; opacity: 0.4;"></div>
137 <div class="jcrop-vline" style="position: absolute; opacity: 0.4;"></div>
138 <div class="jcrop-tracker" style="cursor: move; position: absolute; z-index: 360;"></div>
139
140 </div>
141
142 <div style="width: 100%; height: 100%; z-index: 320; display: none;">
143
144 <div class="ord-n jcrop-dragbar" style="cursor: n-resize; position: absolute; z-index: 370;"></div>
145 <div class="ord-s jcrop-dragbar" style="cursor: s-resize; position: absolute; z-index: 371;"></div>
146 <div class="ord-e jcrop-dragbar" style="cursor: e-resize; position: absolute; z-index: 372;"></div>
147 <div class="ord-w jcrop-dragbar" style="cursor: w-resize; position: absolute; z-index: 373;"></div>
148 <div class="ord-n jcrop-handle" style="cursor: n-resize; position: absolute; z-index: 374; opacity: 0.5;"></div>
149 <div class="ord-s jcrop-handle" style="cursor: s-resize; position: absolute; z-index: 375; opacity: 0.5;"></div>
150 <div class="ord-e jcrop-handle" style="cursor: e-resize; position: absolute; z-index: 376; opacity: 0.5;"></div>
151 <div class="ord-w jcrop-handle" style="cursor: w-resize; position: absolute; z-index: 377; opacity: 0.5;"></div>
152 <div class="ord-nw jcrop-handle" style="cursor: nw-resize; position: absolute; z-index: 378; opacity: 0.5;"></div>
153 <div class="ord-ne jcrop-handle" style="cursor: ne-resize; position: absolute; z-index: 379; opacity: 0.5;"></div>
154 <div class="ord-se jcrop-handle" style="cursor: se-resize; position: absolute; z-index: 380; opacity: 0.5;"></div>
155 <div class="ord-sw jcrop-handle" style="cursor: sw-resize; position: absolute; z-index: 381; opacity: 0.5;"></div>
156
157 </div>
158 </div>
159
160 <div class="jcrop-tracker" style="width: 606px; height: 404px; position: absolute; top: -2px; left: -2px; z-index: 290; cursor: crosshair;"></div>
161 <input type="radio" class="jcrop-keymgr" style="position: fixed; left: -120px; width: 12px;">
162 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" alt="\[Jcrop Example\]" style="display: block; visibility: visible; width: 602px; height: 400px; border: none; margin: 0px; padding: 0px; position: absolute; top: 0px; left: 0px;">
163
164 <div id="preview-pane">
165
166 <div class="preview-container">
167 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" class="jcrop-preview" alt="Preview" style="width: 34113px; height: 22667px; margin-left: -32130px; margin-top: -12013px;">
168 </div>
169
170 </div>
171
172 </div>
173
174
175
176<div class="clearfix"></div>
177</div>
178</div>
179</div>
180</div>
181</body>
182
ANSWER
Answered 2020-Oct-25 at 14:39Seems the job of adding jcrop-holder
div
is performed by the JQuery
code in the <script>
part.
Since inside of your body
tag, there is already a jcrop-holder
div
available, you are having the div
twice when the page loading finishes. i.e. the JQuery
part does what it should do. So, here is the solution I have come up with after debugging for some time:
1<!DOCTYPE html>
2<html lang="en">
3
4<head>
5 <title>Aspect Ratio with Preview Pane | Jcrop Demo</title>
6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
7
8<script src="js/jquery.min.js"></script>
9<script src="js/jquery.Jcrop.min.js"></script>
10<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
11
12<!-- Bootstrap core CSS -->
13<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
14<!-- Custom styles for this template -->
15<link href="css/heroic-features.css" rel="stylesheet">
16
17<!-- Bootstrap core CSS -->
18<link href="vendor/bootstrap[enter image description here][1]/css/bootstrap.min.css" rel="stylesheet">
19
20<!-- Custom styles for this template -->
21<link href="css/heroic-features.css" rel="stylesheet">
22
23<style type="text/css">
24
25/* Apply these styles only when #preview-pane has
26 been placed within the Jcrop widget */
27.jcrop-holder #preview-pane {
28 display: block;
29 position: absolute;
30 z-index: 2000;
31 top: 10px;
32 right: -280px;
33 padding: 6px;
34 border: 1px rgba(0,0,0,.4) solid;
35 background-color: white;
36
37 -webkit-border-radius: 6px;
38 -moz-border-radius: 6px;
39 border-radius: 6px;
40
41 -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
42 -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
43 box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
44}
45
46/* The Javascript code will set the aspect ratio of the crop
47 area based on the size of the thumbnail preview,
48 specified here */
49#preview-pane .preview-container {
50 width: 250px;
51 height: 170px;
52 overflow: hidden;
53}
54
55</style>
56
57
58<script type="text/javascript">
59
60 jQuery(function($){
61
62 // Create variables (in this scope) to hold the API and image size
63 var jcrop_api,
64 boundx,
65 boundy,
66
67 // Grab some information about the preview pane
68 $preview = $('#preview-pane'),
69 $pcnt = $('#preview-pane .preview-container'),
70 $pimg = $('#preview-pane .preview-container img'),
71
72 xsize = $pcnt.width(),
73 ysize = $pcnt.height();
74
75 console.log('init',[xsize,ysize]);
76 $('#target').Jcrop({
77 onChange: updatePreview,
78 onSelect: updatePreview,
79 aspectRatio: xsize / ysize
80 },function(){
81 // Use the API to get the real image size
82 var bounds = this.getBounds();
83 boundx = bounds[0];
84 boundy = bounds[1];
85 // Store the API in the jcrop_api variable
86 jcrop_api = this;
87
88 // Move the preview into the jcrop container for css positioning
89 $preview.appendTo(jcrop_api.ui.holder);
90 });
91
92 function updatePreview(c)
93 {
94 if (parseInt(c.w) > 0)
95 {
96 var rx = xsize / c.w;
97 var ry = ysize / c.h;
98
99 $pimg.css({
100 width: Math.round(rx * boundx) + 'px',
101 height: Math.round(ry * boundy) + 'px',
102 marginLeft: '-' + Math.round(rx * c.x) + 'px',
103 marginTop: '-' + Math.round(ry * c.y) + 'px'
104 });
105 }
106 };
107
108 });
109
110</script>
111
112</head>
113
114
115
116<body style="zoom: 1;">
117<div class="container">
118<div class="row">
119<div class="span12">
120<div class="jc-demo-box">
121 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" id="target" style="display: none; visibility: hidden; width: 602px; height: 400px;">
122
123
124 <div class="jcrop-holder" style="width: 602px; height: 400px; position: relative; background-color: black;">
125
126 <div style="position: absolute; z-index: 600;">
127
128 <div style="width: 100%; height: 100%; z-index: 310; position: absolute; overflow: hidden;">
129
130 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" style="border: none; visibility: visible; margin: 0px; padding: 0px; position: absolute; top: 0px; left: 0px; width: 602px; height: 400px;">
131
132 <div class="jcrop-hline" style="position: absolute; opacity: 0.4;"> </div>
133
134 <div class="jcrop-hline bottom" style="position: absolute; opacity: 0.4;"> </div>
135
136 <div class="jcrop-vline right" style="position: absolute; opacity: 0.4;"></div>
137 <div class="jcrop-vline" style="position: absolute; opacity: 0.4;"></div>
138 <div class="jcrop-tracker" style="cursor: move; position: absolute; z-index: 360;"></div>
139
140 </div>
141
142 <div style="width: 100%; height: 100%; z-index: 320; display: none;">
143
144 <div class="ord-n jcrop-dragbar" style="cursor: n-resize; position: absolute; z-index: 370;"></div>
145 <div class="ord-s jcrop-dragbar" style="cursor: s-resize; position: absolute; z-index: 371;"></div>
146 <div class="ord-e jcrop-dragbar" style="cursor: e-resize; position: absolute; z-index: 372;"></div>
147 <div class="ord-w jcrop-dragbar" style="cursor: w-resize; position: absolute; z-index: 373;"></div>
148 <div class="ord-n jcrop-handle" style="cursor: n-resize; position: absolute; z-index: 374; opacity: 0.5;"></div>
149 <div class="ord-s jcrop-handle" style="cursor: s-resize; position: absolute; z-index: 375; opacity: 0.5;"></div>
150 <div class="ord-e jcrop-handle" style="cursor: e-resize; position: absolute; z-index: 376; opacity: 0.5;"></div>
151 <div class="ord-w jcrop-handle" style="cursor: w-resize; position: absolute; z-index: 377; opacity: 0.5;"></div>
152 <div class="ord-nw jcrop-handle" style="cursor: nw-resize; position: absolute; z-index: 378; opacity: 0.5;"></div>
153 <div class="ord-ne jcrop-handle" style="cursor: ne-resize; position: absolute; z-index: 379; opacity: 0.5;"></div>
154 <div class="ord-se jcrop-handle" style="cursor: se-resize; position: absolute; z-index: 380; opacity: 0.5;"></div>
155 <div class="ord-sw jcrop-handle" style="cursor: sw-resize; position: absolute; z-index: 381; opacity: 0.5;"></div>
156
157 </div>
158 </div>
159
160 <div class="jcrop-tracker" style="width: 606px; height: 404px; position: absolute; top: -2px; left: -2px; z-index: 290; cursor: crosshair;"></div>
161 <input type="radio" class="jcrop-keymgr" style="position: fixed; left: -120px; width: 12px;">
162 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" alt="\[Jcrop Example\]" style="display: block; visibility: visible; width: 602px; height: 400px; border: none; margin: 0px; padding: 0px; position: absolute; top: 0px; left: 0px;">
163
164 <div id="preview-pane">
165
166 <div class="preview-container">
167 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" class="jcrop-preview" alt="Preview" style="width: 34113px; height: 22667px; margin-left: -32130px; margin-top: -12013px;">
168 </div>
169
170 </div>
171
172 </div>
173
174
175
176<div class="clearfix"></div>
177</div>
178</div>
179</div>
180</div>
181</body>
182<body style="zoom: 1;">
183<div class="container">
184 <div class="row">
185 <div class="span12">
186 <div class="jc-demo-box">
187 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" id="target" style="display: none; visibility: hidden; width: 602px; height: 400px;">
188 <div class="jcrop-tracker" style="width: 606px; height: 404px; position: absolute; top: -2px; left: -2px; cursor: crosshair;"></div>
189 <input type="radio" class="jcrop-keymgr" style="position: fixed; left: -120px; width: 12px;">
190 <div id="preview-pane">
191 <div class="preview-container">
192 <img src="https://fast-listings.com/uploaded_images/5f8abd050dcfa7.90503490.jpg" class="jcrop-preview" alt="Preview" style="width: 34113px; height: 22667px; margin-left: -32130px; margin-top: -12013px;">
193 </div>
194 </div>
195 <div class="clearfix"></div>
196 </div>
197 </div>
198 </div>
199</div>
200</body>
201
Just replace everything in the body
and it should be working as expected.
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Code Inspection
Tutorials and Learning Resources are not available at this moment for Code Inspection