modm | modm : a C++20 library generator for AVR and ARM Cortex-M
kandi X-RAY | modm Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
modm Key Features
modm Examples and Code Snippets
Trending Discussions on modm
Trending Discussions on modm
QUESTION
This is a follow up to a question that I had before. I know about the DoRectFloat/RationalRect modules and such, but, I've tried to write proper Haskell and it either doesn't compile, or it compiles and doesn't do what I want.
(These are floating windows that I want) What I want is a layout like
How would I go about writing this?
My current Xmonad Config:
--my XMonad Config
--xterm, contrib, feh, and nitrogen are used here
import XMonad
import Data.Monoid
import XMonad.Util.Run
import XMonad.Layout.Gaps
import XMonad.Util.SpawnOnce
import XMonad.Layout.Spacing
import System.Exit
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers
import XMonad.ManageHook
import qualified DBus as D
import qualified DBus.Client as D
import XMonad.Hooks.DynamicLog
import qualified Codec.Binary.UTF8.String as String
import XMonad.Util.EZConfig(additionalKeys)
import System.IO
import qualified XMonad.StackSet as W
import qualified Data.Map as M
import Graphics.X11.ExtraTypes.XF86
-- The preferred terminal program, which is used in a binding below and by
-- certain contrib modules.
--
myTerminal = "xterm"
-- Whether focus follows the mouse pointer.
myFocusFollowsMouse :: Bool
myFocusFollowsMouse = True
-- Whether clicking on a window to focus also passes the click to the window
myClickJustFocuses :: Bool
myClickJustFocuses = False
-- Width of the window border in pixels.
--
myBorderWidth = 2
-- modMask lets you specify which modkey you want to use. The default
-- is mod1Mask ("left alt"). You may also consider using mod3Mask
-- ("right alt"), which does not conflict with emacs keybindings. The
-- "windows key" is usually mod4Mask.
--
myModMask = mod1Mask
-- The default number of workspaces (virtual screens) and their names.
-- By default we use numeric strings, but any string may be used as a
-- workspace name. The number of workspaces is determined by the length
-- of this list.
--
-- A tagging example:
--
-- > workspaces = ["web", "irc", "code" ] ++ map show [4..9]
--
myWorkspaces = ["1","2","3","4","5","6","7","8","9"]
-- Border colors for unfocused and focused windows, respectively.
--
myNormalBorderColor = "#0a0b11"
myFocusedBorderColor = "#ace5e0"
--soda
------------------------------------------------------------------------
-- Key bindings. Add, modify or remove key bindings here.
--
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $
-- launch a terminal
[ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf)
-- launch dmenu
, ((modm, xK_d ), spawn "dmenu_run")
--launch ff
, ((modm, xK_p ), spawn "brave")
--vol
, ((modm, xK_F8 ), spawn "pactl set-sink-mute @DEFAULT_SINK@ toggle")
, ((modm, xK_i ), spawn "pactl set-sink-port 0 analog-output-speaker")
, ((modm, xK_o ), spawn "pactl set-sink-port 0 analog-output-headphones")
, ((modm, xK_F6 ), spawn "pactl set-sink-volume @DEFAULT_SINK@ 50%")
, ((modm, xK_Up ), spawn "pactl set-sink-volume @DEFAULT_SINK@ +3%")
, ((modm, xK_Down ), spawn "pactl set-sink-volume @DEFAULT_SINK@ -3%")
--, ((0, xK_Right), spawn "xbacklight -dec 10")
--, ((0, xK_Left), spawn "xbacklight -inc 10")
--lol
, ((0, xF86XK_AudioRaiseVolume ), spawn "pactl set-sink-volume @DEFAULT_SINK@ +5%")
, ((0, xF86XK_AudioLowerVolume ), spawn "pactl set-sink-volume @DEFAULT_SINK@ -5%")
, ((0, xF86XK_AudioMute ), spawn "pactl set-sink-mute @DEFAULT_SINK@ toggle")
-- launch gmrun
--, ((modm .|. shiftMask, xK_p ), spawn "gmrun")
, ((modm .|. shiftMask, xK_v ), spawn "virtualbox")
, ((modm .|. shiftMask, xK_b ), spawn "xrandr --output eDP-1 --brightness 0.5")
, ((modm .|. shiftMask, xK_z ), spawn "xrandr --output eDP-1 --brightness 1")
--master settings /gnome
, ((modm .|. shiftMask, xK_f ), spawn "gnome-control-center")
--eq
, ((modm .|. shiftMask, xK_u ), spawn "pulseeffects")
--lock (you need i3lock installed on your system)
, ((modm .|. shiftMask, xK_x ), spawn "i3lock -i ~/.config/i3/spart.png")
--fm
, ((modm .|. shiftMask, xK_g ), spawn "pcmanfm")
-- close focused window
, ((modm .|. shiftMask, xK_c ), kill)
-- Rotate through the available layout algorithms
, ((modm, xK_space ), sendMessage NextLayout)
-- Reset the layouts on the current workspace to default
, ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf)
-- Resize viewed windows to the correct size
, ((modm, xK_n ), refresh)
-- Move focus to the next window
, ((modm, xK_Tab ), windows W.focusDown)
-- Move focus to the next window
, ((modm, xK_j ), windows W.focusDown)
-- Move focus to the previous window
, ((modm, xK_k ), windows W.focusUp )
-- Move focus to the master window
, ((modm, xK_m ), windows W.focusMaster )
-- Swap the focused window and the master window
, ((modm, xK_Return), windows W.swapMaster)
-- Swap the focused window with the next window
, ((modm .|. shiftMask, xK_j ), windows W.swapDown )
-- Swap the focused window with the previous window
, ((modm .|. shiftMask, xK_k ), windows W.swapUp )
-- Shrink the master area
, ((modm, xK_h ), sendMessage Shrink)
-- Expand the master area
, ((modm, xK_l ), sendMessage Expand)
-- Push window back into tiling
, ((modm, xK_t ), withFocused $ windows . W.sink)
-- Increment the number of windows in the master area
, ((modm , xK_comma ), sendMessage (IncMasterN 1))
-- Deincrement the number of windows in the master area
, ((modm , xK_period), sendMessage (IncMasterN (-1)))
-- Toggle the status bar gap
-- Use this binding with avoidStruts from Hooks.ManageDocks.
-- See also the statusBar function from Hooks.DynamicLog.
--
-- , ((modm , xK_b ), sendMessage ToggleStruts)
-- Quit xmonad
, ((modm .|. shiftMask, xK_q ), io (exitWith ExitSuccess))
-- Restart xmonad
, ((modm , xK_q ), spawn "xmonad --recompile; xmonad --restart")
-- Run xmessage with a summary of the default keybindings (useful for beginners)
, ((modm .|. shiftMask, xK_slash ), spawn ("echo \"" ++ help ++ "\" | xmessage -file -"))
]
++
--
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
--
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
--
-- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
--
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
------------------------------------------------------------------------
-- Mouse bindings: default actions bound to mouse events
--
myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
-- mod-button1, Set the window to floating mode and move by dragging
[ ((modm, button1), (\w -> focus w >> mouseMoveWindow w
>> windows W.shiftMaster))
-- mod-button2, Raise the window to the top of the stack
, ((modm, button2), (\w -> focus w >> windows W.shiftMaster))
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modm, button3), (\w -> focus w >> mouseResizeWindow w
>> windows W.shiftMaster))
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
------------------------------------------------------------------------
-- Layouts:
-- You can specify and transform your layouts by modifying these values.
-- If you change layout bindings be sure to use 'mod-shift-space' after
-- restarting (with 'mod-q') to reset your layout state to the new
-- defaults, as xmonad preserves your old layout settings by default.
--
-- The available layouts. Note that each layout is separated by |||,
-- which denotes layout choice.
--
myLayout = tiled ||| Mirror tiled ||| theg ||| Full
where
tiled = spacing 35 $ Tall nmaster delta ratio
theg = gaps [(U,18), (R,23)] $ Tall 1 (3/100) (1/2)
nmaster = 1
ratio = 1/2
delta = 3/100
------------------------------------------------------------------------
-- Window rules:
-- Execute arbitrary actions and WindowSet manipulations when managing
-- a new window. You can use this to, for example, always float a
-- particular program, or have a client always appear on a particular
-- workspace.
--
-- To find the property name associated with a program, use
-- > xprop | grep WM_CLASS
-- and click on the client you're interested in.
--
-- To match on the WM_NAME, you can use 'title' in the same way that
-- 'className' and 'resource' are used below.
-- --> (doRectFloat $ W.RationalRect 0.5 0.5 0.9 0.9)
myManageHook = composeAll . concat $
[ [className =? "mpv" --> doFloat]
, [className =? "xterm" --> (doRectFloat $ W.RationalRect 0.5 0.5 0.4 0.4)]
--, [className =? c --> (doRectFloat $ W.RationalRect 0.5 0.5 0.9 0.9)| c <- mylol]
, [manageDocks]
]
where
myTop = ["xterm htop"]
myTerm = ["xterm"]
myVis = ["xterm vis"]
------------------------------------------------------------------------
-- Event handling
-- * EwmhDesktops users should change this to ewmhDesktopsEventHook
--
-- Defines a custom handler function for X Events. The function should
-- return (All True) if the default handler is to be run afterwards. To
-- combine event hooks use mappend or mconcat from Data.Monoid.
--
myEventHook = mempty
------------------------------------------------------------------------
-- Status bars and logging
-- Perform an arbitrary action on each internal state change or X event.
-- See the 'XMonad.Hooks.DynamicLog' extension for examples.
--
myLogHook = return ()
------------------------------------------------------------------------
-- Startup hook
-- Perform an arbitrary action each time xmonad starts or is restarted
-- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize
-- per-workspace layout choices.
--
-- By default, do nothing.
myStartupHook :: X ()
myStartupHook = do
spawn "nitrogen --restore &"
spawn "picom &"
spawn "xterm vis"
spawn "xsetroot -cursor_name left_ptr"
spawn "xset b off"
------------------------------------------------------------------------
-- Now run xmonad with all the defaults we set up.
-- Run xmonad with the settings you specify. No need to modify this.
--
main = do
xmproc <- spawnPipe "xmobar -x 0 ~/.xmonad/taskbarrc"
xmonad $ docks defaults
-- A structure containing your configuration settings, overriding
-- fields in the default config. Any you don't override, will
-- use the defaults defined in xmonad/XMonad/Config.hs
--
-- No need to modify this.
--
defaults = def {
-- simple stuff
terminal = myTerminal,
focusFollowsMouse = myFocusFollowsMouse,
clickJustFocuses = myClickJustFocuses,
borderWidth = myBorderWidth,
modMask = myModMask,
workspaces = myWorkspaces,
normalBorderColor = myNormalBorderColor,
focusedBorderColor = myFocusedBorderColor,
-- key bindings
keys = myKeys,
mouseBindings = myMouseBindings,
-- hooks, layouts
layoutHook = myLayout,
manageHook = myManageHook,
handleEventHook = myEventHook,
logHook = myLogHook,
startupHook = myStartupHook
}
-- | Finally, a copy of the default bindings in simple textual tabular format.
help :: String
help = unlines ["The default modifier key is 'alt'. Default keybindings:",
"",
"-- launching and killing programs",
"mod-Shift-Enter Launch xterminal",
"mod-p Launch dmenu",
"mod-Shift-p Launch gmrun",
"mod-Shift-c Close/kill the focused window",
"mod-Space Rotate through the available layout algorithms",
"mod-Shift-Space Reset the layouts on the current workSpace to default",
"mod-n Resize/refresh viewed windows to the correct size",
"",
"-- move focus up or down the window stack",
"mod-Tab Move focus to the next window",
"mod-Shift-Tab Move focus to the previous window",
"mod-j Move focus to the next window",
"mod-k Move focus to the previous window",
"mod-m Move focus to the master window",
"",
"-- modifying the window order",
"mod-Return Swap the focused window and the master window",
"mod-Shift-j Swap the focused window with the next window",
"mod-Shift-k Swap the focused window with the previous window",
"",
"-- resizing the master/slave ratio",
"mod-h Shrink the master area",
"mod-l Expand the master area",
"",
"-- floating layer support",
"mod-t Push window back into tiling; unfloat and re-tile it",
"",
"-- increase or decrease number of windows in the master area",
"mod-comma (mod-,) Increment the number of windows in the master area",
"mod-period (mod-.) Deincrement the number of windows in the master area",
"",
"-- quit, or restart",
"mod-Shift-q Quit xmonad",
"mod-q Restart xmonad",
"mod-[1..9] Switch to workSpace N",
"",
"-- Workspaces & screens",
"mod-Shift-[1..9] Move client to workspace N",
"mod-{w,e,r} Switch to physical/Xinerama screens 1, 2, or 3",
"mod-Shift-{w,e,r} Move client to screen 1, 2, or 3",
"",
"-- Mouse bindings: default actions bound to mouse events",
"mod-button1 Set the window to floating mode and move by dragging",
"mod-button2 Raise the window to the top of the stack",
"mod-button3 Set the window to floating mode and resize by dragging"]
ANSWER
Answered 2021-Jan-28 at 15:37When starting the three windows, use xterm
's -class
option to modify the WM_CLASS
property it attaches to its window, choosing a different and unique class for each of the three. Then you can select for that class in your manage hook to only match the right window.
QUESTION
how to make this key binding so that it also focuses on the moved window?
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_h, xK_l] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
ANSWER
Answered 2020-Nov-15 at 19:30Use shiftAndView i = W.view i . W.shift i
instead of W.shift
like this:
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_h, xK_l] [0..]
, let shiftAndView i = W.view i . W.shift i
, (f, m) <- [(W.view, 0), (shiftAndView, shiftMask)]]
QUESTION
I am using XMonad.Layout.Reflect together with XMonad.Layout.MultiToggle to flip my layout left-right when needed. However, when any layout is reflected, my keybinds for shrinking and expanding the layout, eg.
...
((modm, xK_h), sendMessage Shrink),
((modm, xK_l), sendMessage Expand),
...
behaves as they are inversed.
So, what I want is a way to remap my keys, or maybe use a function instead of sendMessage that somehow detects the state of the layout and chooses Shrink/Expand depending on that.
Now I know that checking eg. global state variables (of which there are no such thing I guess) is not very Haskelly, so I am at a little bit of a loss on how to do this. I've considered XMonad.Actions.PerWorkspaceKeys, but it seems to do a match against the entire Workspace name. Another route could be to add/delete keybinds in defaultConfig, but again - I'm not sure this is even doable (it seems messy anyways).
Any ideas on how to approach this anyone? I know Haskell on the level of having read the "Learn you a Haskell..." book from beginning to end and making smallish programs based on that.
ANSWER
Answered 2020-Jun-09 at 21:42One way to do it is using the layout description to find out whether it has been reflected, following this blog post by Thomas Churchman:
import qualified XMonad.StackSet as S
import Data.List (isInfixOf)
getActiveLayoutDescription :: X String
getActiveLayoutDescription = do
workspaces <- gets windowset
return $ description . S.layout . S.workspace . S.current $ workspaces
The key bindings would then look like this:
((modm, xK_h), do
layoutDesc <- getActiveLayoutDescription
if "ReflectX" `isInfixOf` layoutDesc
then sendMessage Expand
else sendMessage Shrink
,
((modm, xK_l), do
layoutDesc <- getActiveLayoutDescription
if "ReflectX" `isInfixOf` layoutDesc
then sendMessage Shrink
else sendMessage Expand
),
Side notes:
my keybinds for shrinking and expanding the layout [...] behaves as they are inversed.
While what you want to do makes perfect sense, it is worth mentioning that this behaviour happens because reflecting a layout will also reflect the position of the master pane. Since Shrink
and Expand
act on the master pane, they will appear to be inverted, as far as absolute horizontal coordinates go, if you are using a layout like Tall
, in which the master pane is on the left of the screen. Different layouts might be affected differently.
Now I know that checking eg. global state variables (of which there are no such thing I guess) is not very Haskelly, so I am at a little bit of a loss on how to do this.
This approach is not unthinkable, and XMonad.Util.ExtensibleState
is meant for setting up this sort of thing. In this case, though, I feel using a stateful flag is be way more trouble than it's worth.
QUESTION
I've tried to detect this manually by:
myHook :: Event -> X All
myHook e = do
liftIO $ logToTmpFile $ show e
pure $ All True
However on the keypress of modm
(hyper
/windows
) it just shows:
PropertyEvent {ev_event_type = 28, ev_serial = 12080, ev_send_event = False, ev_event_display = Display 0x0000000000df2340, ev_window = 27262982, ev_atom = 353, ev_time = 20662387, ev_propstate = 0}
Which seems rather generic, different keys seem to also emit the same event.
Upon inspection of the XMonad source, it seems 'events' only occur for keystrokes that are 'registered' to be listened to.
ANSWER
Answered 2019-Jan-20 at 11:34To register a 'keystroke':
myStartupHook :: X ()
myStartupHook = do
XConf { display = dpy, theRoot = rootw } <- ask
myKeyCode <- io $ (keysymToKeycode dpy xK_Super_R)
io $ grabKey dpy (myKeyCode) anyModifier rootw True grabModeAsync grabModeAsync
And
myHook :: Event -> X All
myHook e = do
liftIO $ logToTmpFile $ show e
pure $ All True
And then add these to your startupHook
and handleEventHook
values in the config.
I see the following output:
KeyEvent {ev_event_type = 3, ev_serial = 2866, ev_send_event = False, ev_event_display = Display 0x0000000001217340, ev_window = 1056, ev_root = 1056, ev_subwindow = 25166105, ev_time = 4248223, ev_x = 1014, ev_y = 1038, ev_x_root = 1014, ev_y_root = 1038, ev_state = 64, ev_keycode = 134, ev_same_screen = True
QUESTION
I'm trying to understand how XMonad configuration functions are evaluated. The first example is from Xmonad docs:
import qualified Data.Map as M
--
main = xmonad $ defaultConfig {
--
, keys = \c -> mykeys c `M.union` keys defaultConfig c
--
}
where
mykeys (XConfig {modMask = modm}) = M.fromList $
[ ((modm , xK_x), spawn "xlock") ]
The type of keys is a function: keys :: !(XConfig Layout -> Map (ButtonMask, KeySym) (X ()))
The question here is evaluation order. keys
returns Map when applied to some XConfig
, and then Map we've got should be applied to c
(if I get it right), but how Map can be applied to something?
ANSWER
Answered 2018-Dec-22 at 14:51Your description isn't quite correct. keys
is a record field.
When you have a record type R
with a field foo :: T
, then foo
itself (used as a value) has the type R -> T
(it's a record accessor function).
Since keys
is a field of XConfig
, its type is actually
keys :: XConfig l -> !(XConfig Layout -> Map (ButtonMask, KeySym) (X ()))
In
keys defaultConfig c
We extract the keys
field from defaultConfig
. The value stored in this field is itself a function, which we apply to c
to get a Map
.
QUESTION
I have a function which I'd like to be able to pass a class to and have it return the same type as that class.
Currently, the best way I've found is like so:
protected modClass(modMe: CLASS_TYPE): CLASS_TYPE {
console.log(modMe);
return modMe;
}
const modded = modClass(new SomeClass());
The above isn't awful, it does work, but it's not really returning the type of the class passed to the function so much as having it predefined and refusing to take any other class type.
What I'd like to be able to do (for example) is this:
const modded = modClass(new SomeClass());
console.log(typeof modded); // SomeClass;
Is there anyway to make a function which returns whatever the type of one of it's arguments is in TypeScript?
Edit: I should mention, I'm not just trying to have the type be correct, but be checked. I could have the modClass function return type any and typeof
would be correct. It just wouldn't have any real type checking.
ANSWER
Answered 2018-Sep-15 at 19:00typeof
is the Javascript operator when used in expressions and will return object
for classes as it is supposed to do.
As for your function, the generic parameter will be inferred correctly by the compiler you don't have to specify it explicitly. (Changed the name to conform to conventions but it should work regardless)
class SomeClass{
bar(){}
}
function modClass(modMe: T): T {
console.log(modMe);
return modMe;
}
const modded = modClass(new SomeClass()) // modded is SomeClass
modded.bar()
QUESTION
This is my first post so please "Go" easy on me. :) ... I am quite familiar with many traditional programming languages but I am new to Go and having trouble understanding the use of slices and ranges. The program code and comments below illustrate my consternation. Thank you!
package main
import (
"fmt"
"time"
)
type myStruct struct {
Name string
Count int
}
Wrote my own Mod function because I could not find on in the Go libraries.
func modMe(mod int, value int) int {
var m int
var ret int
m = value / mod
ret = value - m*mod
return ret
}
func main() {
mod := 4
cnt := 16
fmt.Printf("Record mod is %d\r\n", mod)
Declare a structure array and add some records
chartRecords := []myStruct{}
for i := 0; i<=cnt ;i++ {
n := myStruct{Count: i, Name: fmt.Sprintf("Joe%2d", i)} //Load some data
chartRecords = append(chartRecords,n)
}
Loading the data produces the output that I expect
fmt.Printf("======ORIGINAL LOADED VALUES========\r\n")
i := 0
for _, elem := range chartRecords {
fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name) //Print out original values in the range
i = i + 1
}
Now I modify the values and print them to see that they appear modified. This looks as expected.
fmt.Printf("======MODIFIED VALUES EXPECTED========\r\n")
i = 0
for _, elem := range chartRecords { //looping thru the range of the data records
mm := modMe(mod, i) //modMe is my function to return the Mod of a number based on moduls 'mod'
elem.Count = mm //assigning the new mod value to Count
fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name) //Print out this elem.Count element in the range
i = i + 1
}
Now I simply loop through the same range again and print the same thing out. But the output shows the original values. I don't understand why this is happening. I'm guessing that it has something to do with slices and adding values rather than replacing the values.
fmt.Printf("======CHECK AGAIN AND VALUES ARE BACK TO ORIGINAL========\r\n") //Now lets loop through the same range
i = 0
for _, elem := range chartRecords {
fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name) //Print out this elem.Count element in the range
i = i + 1
} //But this output shows the original values WHY??
time.Sleep(60 * time.Second)
}
The output looks like this... Screenshot Output
Thanks in advance for your advice.
ANSWER
Answered 2018-Jun-29 at 16:39The Go Programming Language Specification
For statements with range clause
A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.
The Go Programming Language Specification is an easy read.
Put the updated elem
iteration variable back in the chartRecords
slice:
for i, elem := range chartRecords {
elem.Count = modMe(mod, i)
chartRecords[i] = elem
fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name)
}
QUESTION
I created a jsp page that shows me the list of doctors (medecin in french) contained in my mysql database via the hibernate framework and struts2 .
I have a delete button supprimer
(in french), to remove a doctor, and a button , modifier
, to edit the doctor's data .
The edit button , modifier
, will take all the datas (id , nom , prenom etc..) of the selectionned doctor and put it in a form so i can update it .
ListedesMedecins.jsp
my class MedecinDAO with the required method (select , update , delete , list)
public Medecin getMedecin(Integer idMedecin) {
log.info("********** Debut getMedecin MedecinDAO **********");
Medecin Medecin = null;
Session session = SessionFactoryUtil.getInstance().openSession();
try {
Medecin = (Medecin) session.get(Medecin.class, idMedecin);
return Medecin;
} catch (Exception e) {
e.printStackTrace();
log.fatal(e.getMessage());
return null;
} finally {
session.close();
log.info("********** Fin getMedecin MedecinDAO **********");
}
}
public boolean saveMedecin(Medecin Medecin) {
log.info("********** Debut saveMedecin MedecinDAO **********");
Session session = SessionFactoryUtil.getInstance().openSession();
Transaction trans = session.beginTransaction();
try {
session.save(Medecin);
trans.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
log.fatal(e.getMessage());
trans.rollback();
return false;
} finally {
session.close();
log.info("********** Fin saveMedecin MedecinDAO **********");
}
}
public boolean updateMedecin(Medecin Medecin) {
log.info("********** Debut updateMedecin MedecinDAO **********");
Session session = SessionFactoryUtil.getInstance().openSession();
Transaction trans = session.beginTransaction();
try {
session.update(Medecin);
trans.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
log.fatal(e.getMessage());
return false;
} finally {
session.close();
log.info("********** Fin updateMedecin MedecinDAO **********");
}
}
public boolean deleteMedecin(Medecin Medecin) {
log.info("********** Debut deleteMedecin MedecinDAO **********");
Session session = SessionFactoryUtil.getInstance().openSession();
try {
Transaction trans = session.beginTransaction();
session.delete(Medecin);
trans.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
log.fatal(e.getMessage());
return false;
} finally {
session.close();
log.info("********** Fin deleteMedecin MedecinDAO **********");
}
}
public List allmedecin(){
List medecin = null;
Session session = SessionFactoryUtil.getInstance().openSession();
String registr = "from Medecin";
Query query = session.createQuery(registr);
medecin=query.list();
return medecin;
}
And finally my action class , formMedAction.java
//getters,setters...
//this method is for adding Medecin/doctors
public String Ajoutmed() {
MedecinDAO medDAO= MedecinDAO.getInstance();
Medecin M = new Medecin();
M.setIdmed(idmed);
M.setNom(nom);
M.setPrenom(prenom);
M.setContact(contact);
M.setSpecialite(specialite);
medDAO.saveMedecin(M);
return SUCCESS;
}
// return list of all medecin in the table
public String Listmed() throws Exception {
MedecinDAO medDAO = MedecinDAO.getInstance();
Medecin = medDAO.allmedecin();
return SUCCESS;
}
// Method I created to delete the data, but I'm not sure if it correct
public String Supmed() {
MedecinDAO medDAO = MedecinDAO.getInstance();
Medecin M = new Medecin();
M.getIdmed();
M.getNom();
M.getPrenom();
M.getContact();
M.getSpecialite();
medDAO.deleteMedecin(M);
return SUCCESS;
}
public string Modmed () {
//dont know what to do for the modifier/edit action , need your help
return SUCCESS;
}
Need your help Thanks
EDIT !
Find a way to delete a doctor with this code in MedecinDAO :
public Medecin deleteMedecin(Integer idmed) {
log.info("********** Debut deleteMedecin MedecinDAO **********");
Session session = SessionFactoryUtil.getInstance().openSession();
Transaction trans = session.beginTransaction();
Medecin m = (Medecin) session.load(Medecin.class, idmed);
session.delete(m);
trans.commit();
return m;
}
And adding this in the action class
public String Supmed() {
MedecinDAO medDAO = MedecinDAO.getInstance();
Medecin m = new Medecin();
m = medDAO.deleteMedecin(getIdmed());
return SUCCESS;
}
And in JSP button action
now i need to know how to edit
ANSWER
Answered 2017-May-08 at 10:55Edit should be the similar way like you did delete . First you can get Medecin
object you wan to update :
Medecin med = (Medecin) session.get(Medecin.class, idmed);
med.setNom("Andrea"); //set new values of your columns
After you set properties you want to update:
public Medecin updateMedecin(Medecin updatedObject) {
log.info("********** Debut updateMedecin MedecinDAO **********");
Session session = SessionFactoryUtil.getInstance().openSession();
Transaction trans = session.beginTransaction();
session.save(updatedObject);
trans.commit();
return updatedObject;
}
EDITED: If you need to set the value of the selected Medecin Object in new a JSP page, first you need a form to update columns, second you have to pass idMed to form page,
JSP button for edit action:
Form page:
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install modm
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page